package com.ty.web.controller;

import com.ty.model.AjaxResult;
import com.ty.web.spring.config.properties.TyProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

/**
 * 处理流媒体服务MediaMTX的请求
 *
 * @Author Tommy
 * @Date 2024/5/23
 */
@RestController
@RequestMapping("/rest/mediamtx")
@Slf4j
public class MediaMTXController {

    @Autowired
    private TyProperties tyProperties;

    @RequestMapping("/record/complete")
    public AjaxResult recordComplete(String path) throws Exception {
        File vfile = new File(tyProperties.getMediamtxPath() + path);
        boolean exist = vfile.exists();
        log.debug("Mediamtx Record Complete {} {}", vfile.getPath(), exist);

        // 读首/尾帧图像
        if (exist) {
            VideoCapture cap = null;
            Mat mat = null;
            long begin = System.currentTimeMillis();
            try {
                cap = new VideoCapture(vfile.getPath());
                if (cap.isOpened()) {
                    if (!tyProperties.getHandleFirstFrame()) { // 设置帧数到最后1秒
                        int skipFrames = setLastSecondFrames(cap);
                        log.debug("视频流 {} 最后1秒帧数: {}", path, skipFrames);
                    }
                    mat = new Mat();
                    boolean ret = cap.read(mat);
                    if (ret) {
                        String vfileName = FilenameUtils.getBaseName(vfile.getPath());
                        String imgPath = tyProperties.getVrootPath() + vfile.getParentFile().getName() + File.separator + getSecond(vfile.lastModified()) + ".jpg";
                        Imgcodecs.imwrite(imgPath, mat);
                        log.debug("Save帧图片: {}", imgPath);
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            } finally {
                if (null != mat) {
                    mat.release();
                }
                if (null != cap) {
                    cap.release();
                }
            }
            long end = System.currentTimeMillis();
            log.debug("视频帧处理耗时：{}\t{}ms.", path, end - begin);
        }
        return AjaxResult.success();
    }

    int getSecond(long timeMs) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(timeMs));
        return calendar.get(Calendar.SECOND);
    }

    int setLastSecondFrames(VideoCapture cap) {
        double fps = cap.get(Videoio.CAP_PROP_FPS);
        double totalFrames = cap.get(Videoio.CAP_PROP_FRAME_COUNT);
        int skipFrames = (int) (totalFrames - fps / 2);
        cap.set(Videoio.CAP_PROP_POS_FRAMES, skipFrames); // 跳过{skipFrames}帧后，再获取图像
        return skipFrames;
    }
}
